import router from "@/router";
import currencyRoutes from "../../router/modules/currencyRoutes";
import { PermissionRoute } from "/app.config.js";
import asyncRoutesLib from "../../router/modules/nav-test.js";
function extractRoute(route, permissionArr) {
  let arrNew = [];
  for (let item of route) {
    let itemNew = { ...item }; //解决浅拷贝共享同一内存地址
    if (permissionArr.includes(itemNew.name)) {
      if (itemNew.children) {
        itemNew.children = extractRoute(itemNew.children, permissionArr);
      }
      arrNew.push(itemNew);
    }
  }
  return arrNew;
}
const permission = {
  namespaced: true,
  state: {
    routes: null,
  },
  mutations: {
    setRoutes(state, addRoutes) {
      state.routes = [...currencyRoutes, ...addRoutes];
    },
  },
  actions: {
    async MergeRoutes({ state, rootState, commit, dispatch }) {
      // let loginLoading = ElLoading.service({
      //   lock: true,
      //   text: "正在登录...",
      //   background: "rgba(0, 0, 0, 0.7)"
      // });
      // console.log(state, rootState);
      // 有路由控制->请求权限再合并    无路由权限直接合并
      let asyncRoutes = [];
      // 权限路由
      if (PermissionRoute) {
        let { permission: permissionArr } = await dispatch(
          "User/getUserInfo",
          {},
          {
            root: true,
          }
        );
        asyncRoutes = extractRoute(asyncRoutesLib, permissionArr);
      }
      // 无权限控制
      else {
        asyncRoutes = asyncRoutesLib;
      }
      // TODO
      // asyncRoutes.push({ path: '/:pathMatch(.*)*', redirect: "/404",meta: { hidden: true } });
      router.addRoute(...asyncRoutes);
      // router.addRoute({ path: '/:pathMatch(.*)*', redirect: "/404",meta: { hidden: true } });
      commit("setRoutes", asyncRoutes);
      // router.push('/nav-test/nav2/nav2-1')
      return state.routes;
    },
  },
};
export default permission;
